const standardizeObj = require('../util/standardizeObj');
const obj2excel = require('../util/obj2excel');
const makeList = require('../util/makeList');
const throttle = require('../util/throttle');

const submitFeed = require('../mws/feeds/SubmitFeed');
const getFeedSubmissionResult = require('../mws/feeds/GetFeedSubmissionResult');
const getMatchingProductForId = require("../mws/feeds/GetMatchingProductForId");

const AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-2'});
const s3 = new AWS.S3();

const d = {};

const products_standardize_mapping = {
  feedProductType: "feed_product_type",
  itemSKU: "item_sku",
  abc: "__DELETED__",
};

const inventory_standardize_mapping = {

};

function standardizeObject(productList, mapping) {
  return productList.map(item => {
    return standardizeObj.standardizeObj(mapping, item, false);
  });
}

function setAttribute(productList, attrib_name, attrib_value){
  return productList.map(item => {
    if (!item[attrib_name] || item[attrib_name] === "") { // JM: 保留原始配置如果提交时已经包含
      item[attrib_name] = attrib_value;
    }
    return item;
  });
}

function upload(params) { new Promise((resolve, reject) => {
  s3.upload(params, function (err, data) {
    if (err) {
      console.log(err);
      reject(err);
    } else {
      console.log(data);
      resolve(data);
    }
  });
});
}

d.submitFeedToAmazon = async function (options, payloads){
  const marketplaceid = options.marketplaceid;
  const feedType = options.feedtype;
  const productType = options.producttype;
  const sellerId = options.sellerid;
  const mwsAuthToken = options.mwsauthtoken;
  const fileName = options.fileName;

  const products = makeList(payloads);

  let mwsFeedType;
  let feedObject;
  let template_name;
  let template_header_row_count;

  if (feedType === "LST") {
    mwsFeedType = "_POST_FLAT_FILE_LISTINGS_DATA_"; // "_POST_PRODUCT_DATA_";
    template_name = `product_${productType}`;
    template_header_row_count = 3;
    feedObject = standardizeObject(products, products_standardize_mapping);
    feedObject = setAttribute(feedObject, "update_delete", 'Update');
  }
  else if (feedType === "COMB") {
    mwsFeedType = "_POST_FLAT_FILE_LISTINGS_DATA_"; // "_POST_PRODUCT_DATA_";
    template_name = `product_${productType}`;
    template_header_row_count = 3;
    feedObject = standardizeObject(products, products_standardize_mapping);
    feedObject = setAttribute(feedObject, "update_delete", 'PartialUpdate');
  }
  else if (feedType === "DEL") {
    mwsFeedType = "_POST_FLAT_FILE_INVLOADER_DATA_";
    template_name = `inventoryloader`;
    template_header_row_count = 1;
    feedObject = standardizeObject(products, inventory_standardize_mapping);
    feedObject = setAttribute(feedObject, "add-delete", 'x');
  }
  else if (feedType === "DEACT") {
    mwsFeedType = "_POST_FLAT_FILE_INVLOADER_DATA_";
    template_name = "inventoryloader";
    template_header_row_count = 1;
    feedObject = standardizeObject(products, inventory_standardize_mapping);
    feedObject = setAttribute(feedObject, "add-delete", 'd');
  }
  else if (feedType === "INV") {
    mwsFeedType = "_POST_FLAT_FILE_INVLOADER_DATA_";
    template_name = `priceinventory`;
    template_header_row_count = 1;
  }
  else {
    throw Error(`unknown feed type ${feedType}`);
  }

  const xlsx = await obj2excel.obj2excel(template_name, feedObject, template_header_row_count);
  await xlsx.writeFile(".\\spec\\resources\\aaa_1111.xlsx");
  const xlsx_buffer = await xlsx.writeBuffer();

  console.log('Ready to upload template file with product info into S3')
   const params = {
     "Body": xlsx_buffer,
     "Bucket": 'mws.feed.log.dev',
     "Key": fileName + '.xlsx',
     "ACL": "public-read" //https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property
   };
    await upload(params);

    console.log('upload is done');

  const json = await submitFeed.submitFeed(sellerId, mwsAuthToken, mwsFeedType, xlsx_buffer, [marketplaceid]);
  return {
    "FeedSubmissionId": json["FeedSubmissionInfo"]["FeedSubmissionId"],
    "FeedAmazonType": json["FeedSubmissionInfo"]["FeedType"],
    "FeedType": feedType,
    "SubmittedDate": json["FeedSubmissionInfo"]["SubmittedDate"],
    "FeedProcessingStatus": json["FeedSubmissionInfo"]["FeedProcessingStatus"],
  };
};

d.handleFeedCallback = async function (ctx, options, payloads){
  const sellerId = ctx.sellerId;
  const mwsAuthToken = ctx.mwsAuthToken;

  const submissionId = payloads.submissionId;
  const json = await throttle.getFeedSubmissionResultQueue.append(getFeedSubmissionResult.getFeedSubmissionResult, sellerId, mwsAuthToken, submissionId);
  /*{
        "data": [
            {
                "original-record-number": "1",
                "sku": "PTCASE002",
                "error-code": "8567",
                "error-type": "Error",
                "error-message": "SKU PTCASE002 does not match any ASIN and contains invalid values for attributes required for creation of a new ASIN. New ASIN creation requires the following attributes, for which this SKU provided invalid attribute value(s): standard_product_id."
            }
        ],
        "Headers": {
            "x-mws-quota-max": "60.0",
            "x-mws-quota-remaining": "60.0",
            "x-mws-quota-resetson": "2020-12-26T17:09:00.000Z",
            "x-mws-timestamp": "2020-12-26T16:24:59.175Z",
            "content-type": "text/plain",
            "content-charset": "unknown",
            "content-length": "427",
            "content-md5": "xI8rLAzQM9lVLMSoCmL/Kw==",
            "date": "Sat, 26 Dec 2020 16:24:59 GMT"
        },
        "StatusCode": 200
    }*/
  return {
    failures: json.data
  };
};

d.handleFeedCallbackAfterSuccess = async function (ctx, payloads) {
  const sellerId = ctx.sellerId;
  const mwsAuthToken = ctx.mwsAuthToken;  

  const idList = payloads.idList;
  const marketPlaceId = payloads.marketPlaceId;
  //const marketPlaceId = 'ATVPDKIKX0DER';
  //var idList = ['602c8461a85c47ed15aa732f-6765567567', '602c8461a85c47ed15aa732f-6765567569'];

  const json = await throttle.getMatchingProductForIdQueue.append(getMatchingProductForId.getMatchingProductForId, sellerId, mwsAuthToken, marketPlaceId, idList);
  
  console.log('Start to get product info from aws')
  console.log(JSON.stringify(json))
  console.log('End to get product info from aws')

  const skuAsinPair = json.map(item => {
    return {  
      asin: item.Products.Product.Identifiers.MarketplaceASIN.ASIN,
      id: item.Id,
  }});
  return skuAsinPair;
};

module.exports = d;